package com.hangsu.train.components.service.impl;


import com.hangsu.train.components.dao.OrgDao;
import com.hangsu.train.components.entity.Org;
import com.hangsu.train.components.params.OrgAddParam;
import com.hangsu.train.components.service.OrgService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

@Service
public class OrgServiceImpl implements OrgService {

    private OrgDao orgDao;

    @Resource
    public void setOrgDao(OrgDao orgDao) {
        this.orgDao = orgDao;
    }

    @Override
    public List<Org> tree() {
        return orgDao.getALL();
    }

    @Transactional
    @Override
    public boolean create(OrgAddParam param) {
        Org organization = orgDao.selectByPrimaryKey(param.getParentId());
        Assert.notNull(organization, "父节点不存在");
        orgDao.incLeft(organization.getLeft());
        orgDao.incRight(organization.getLeft());
        Org org = new Org();
        org.setName(param.getName());
        org.setLeft(organization.getLeft() + 1);
        org.setRight(organization.getLeft() + 2);
        org.setIsEdit(1);
        org.setParentId(param.getParentId());
        orgDao.insert(org);
        return false;
    }

    @Transactional
    @Override
    public boolean del(long id) {
        Org organization = orgDao.selectByPrimaryKey(id);
        Assert.notNull(organization, "当前节点不存在");
        orgDao.del(organization.getLeft(), organization.getRight());
        int width = organization.getRight() - organization.getLeft() + 1;
        orgDao.reduceLeft(organization.getRight(), width);
        orgDao.reduceRight(organization.getRight(), width);
        return true;
    }
}